package com.blog.controller;

import com.blog.aop.MyStartupRunner;
import com.blog.common.FlieResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Objects;
import java.util.UUID;

/**
 * @author jiafujun
 * 2020-05-15 16:33:13
 **/
@RestController
@RequestMapping("/upload")
public class UploadFileController {
    private String[] imgtype = {".jpg", ".jpeg", ".png", ".gif",".bmp", ".webp"};

    @RequestMapping(value = "/imgUpLoad", method = RequestMethod.POST)
    public FlieResult imgUpLoad(@RequestParam("editormd-image-file") MultipartFile file) throws IOException {
        if (file.isEmpty()) {
            return FlieResult.error("上传失败，请选择文件！");
        }
        String fileName = file.getOriginalFilename();
        String suffixName = fileName.substring(Objects.requireNonNull(fileName).lastIndexOf("."));
        if (!Arrays.asList(imgtype).contains(suffixName)) {
            return FlieResult.error("上传失败，请上传正确的图片格式！");
        }
        fileName = UUID.randomUUID() + suffixName;
        String filePath = MyStartupRunner.imgFlie + fileName;
        File dest = new File(filePath);
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }

        file.transferTo(dest);

        return FlieResult.ok("/OTA/" + fileName);
    }

}
